<template>
  <el-dialog
    :append-to-body="true"
    :close-on-click-modal="false"
    :before-close="cancel"
    :visible.sync="dialog"
    @open="openLogin"
    width="380px"
    id="login"
  >
    <template>
      <el-tabs v-model="activeName" @tab-click="handleClick" class="tab">
        <el-tab-pane label="账户登录" name="first">
          <el-form ref="loginForm" :model="loginForm" :rules="loginRules">
            <el-form-item prop="username">
              <el-input
                v-model="loginForm.username"
                maxlength="20"
                style="width: 100%"
                placeholder="请输入账号"
              />
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                v-model="loginForm.password"
                maxlength="20"
                type="password"
                style="width: 100%"
                placeholder="请输入密码"
              />
            </el-form-item>
            <el-form-item prop="code">
              <el-input
                v-model="loginForm.code"
                auto-complete="off"
                placeholder="验证码"
                style="width: 63%"
                @keyup.enter.native="handleLogin"
              >
              </el-input>
              <div class="login-code">
                <img :src="codeUrl" @click="getCode" />
              </div>
            </el-form-item>
          </el-form>
          <el-button :loading="loading" @click="handleLogin" class="line-btn"
            >登录</el-button
          >
          <div class="mar-top-20">
            <template>
              <el-checkbox v-model="loginForm.rememberMe">记住密码</el-checkbox>
            </template>
          </div>
          <div class="mar-top-20">
			<div class="el-checkbox">
				<el-checkbox v-model="checked1" style="vertical-align:middle"></el-checkbox>
				<span class="el-checkbox__label" style="cursor: pointer;vertical-align:middle" @click="readUserAgree()">登录代表您已阅读并同意《用户服务协议及隐私政策》并使账号登录</span>
			</div>
          </div>
        </el-tab-pane>

        <el-tab-pane label="扫码登录" name="second">
          <div style="" class="code-box">
            <div id="qrcode" ref="qrCodeUrl" v-show="codeStatus !== 1"></div>
            <img :src="qrSuccess" v-show="codeStatus === 1" />
            <div class="failure dl-column center" v-show="codeStatus === -1">
              <p>授权登录时间已过期</p>
              <el-button
                type="success"
                round
                size="small"
                @click="refreshCode()"
                >刷新
              </el-button>
            </div>
          </div>
          <div v-show="codeStatus !== 1">
            <div
              style="
                width: 160px;
                height: 40px;
                line-height: 40px;
                text-align: center;
                margin: 0px auto;
                font-size: 15px;
              "
            >
              打开<span style="color: #0068b6">技能培训App</span>
            </div>
            <div
              style="
                width: 220px;
                height: 40px;
                text-align: center;
                margin: 0px auto;
                font-size: 13px;
              "
            >
              在「首页」页右上角打开扫一扫
            </div>
          </div>
          <div v-show="codeStatus === 1">
            <div
              style="
                width: 220px;
                height: 40px;
                text-align: center;
                margin: 0px auto;
                font-size: 13px;
              "
            >
              扫描成功，请在手机上确认是否授权登录
            </div>
          </div>

          <div class="mar-top-20">
            <div class="el-checkbox">
            	<el-checkbox v-model="checked1" style="vertical-align:middle"></el-checkbox>
            	<span class="el-checkbox__label" style="cursor: pointer;vertical-align:middle" @click="readUserAgree()">登录代表您已阅读并同意《用户服务协议及隐私政策》并使账号登录</span>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </template>
  </el-dialog>
</template>

<script>
import qrSuccess from '../assets/image/qrSuccess.png';
import { getCodeImg, getScanCode, getScanResult } from '@/api/login';
import { encrypt } from '@/utils/rsaEncrypt';
import Config from '@/config';
import QRCode from 'qrcodejs2';

export default {
  components: {},
  data() {
    return {
      checked1: true,
      qrSuccess: qrSuccess,
      loading: false,
      dialog: false,
      codeUrl: '',
      codeStatus: 0, // 0- 未扫描 1-扫描成功 2-确认登录 -1已过期
      effectiveTime: 60, // 过期时间
      qrCodeTimer: null,
      code: null,
      loginForm: {
        username: '',
        password: '',
        rememberMe: false,
        code: '',
        uuid: '',
        clientId: Config.clientId,
      },
      activeName: 'first',
      qrCodeShow: false,
      loginRules: {
        username: [{ required: true, trigger: 'blur', message: '请输入账号' }],
        password: [{ required: true, trigger: 'blur', message: '请输入密码' }],
        code: [
          { required: true, trigger: 'change', message: '验证码不能为空' },
        ],
      },
    };
  },
  created() {},
  methods: {
	readUserAgree(){
	},
    cancel() {
      this.dialog = false;
      this.loginForm = {
        username: '',
        password: '',
        rememberMe: false,
        code: '',
        uuid: '',
        clientId: Config.clientId,
      };
      this.clearCode();
      this.clearTimer(this.qrCodeTimer);
      this.activeName = 'first';
      this.qrCodeShow = false;
    },
    handleClick(tab, event) {
      if (this.activeName === 'second' && !this.qrCodeShow) {
        this.qrCodeShow = true;
        this.creatQrCode();
      }
    },
    openLogin() {
      this.$nextTick(() => {
        this.getCode();
        this.getStorage();
      });
    },
    //创建二维码
    creatQrCode() {
      this.initVariable();
      getScanCode().then((data) => {
        const scanUrl = Config.baseURL + '/auth/app/scan-code?code=' + data;
        new QRCode(this.$refs.qrCodeUrl, {
          text: scanUrl,
          width: 160,
          height: 160,
          colorDark: '#000000',
          colorLight: '#ffffff',
          correctLevel: QRCode.CorrectLevel.H,
        });
        this.code = data;
        this.getCodeStatus();
      });
    },
    //获取扫描结果
    getCodeStatus() {
      const qrCodeTimer = window.setInterval(() => {
        if (this.effectiveTime >= 1) {
          getScanResult(this.code).then((res) => {
            if (res.status === 1) {
              this.codeStatus = 1;
            } else if (res.status === 2) {
              this.$store.dispatch('ScanLogin', res).then(() => {
                this.cancel();
                location.reload();
              });
            }
          });
        } else {
          this.codeStatus = -1;
          this.clearTimer(qrCodeTimer);
        }
        this.effectiveTime--;
      }, 1000);
      this.qrCodeTimer = qrCodeTimer;
    },
    initVariable() {
      this.codeStatus = 0;
      this.effectiveTime = 60;
    },
    //刷新验证码
    refreshCode() {
      this.clearCode();
      this.creatQrCode();
    },
    //清除二维码
    clearCode() {
      const codeHtml = document.getElementById('qrcode');
      codeHtml.innerHTML = '';
    },
    //清楚定时器
    clearTimer(qrCodeTimer) {
      if (qrCodeTimer) {
        window.clearInterval(qrCodeTimer);
      }
    },
    getCode() {
      getCodeImg().then((res) => {
        this.codeUrl = 'data:image/gif;base64,' + res.img;
        this.loginForm.uuid = res.uuid;
      });
    },
    getStorage() {
      const username = localStorage.getItem('username');
      let password = localStorage.getItem('password');
      const rememberMe = localStorage.getItem('rememberMe');
      this.cookiePass = password === null ? '' : password;
      password = password === null ? this.loginForm.password : password;
      this.loginForm = {
        username: username === null ? this.loginForm.username : username,
        password: password,
        rememberMe: rememberMe === null ? false : Boolean(rememberMe),
        code: '',
      };
    },
    handleLogin() {
		if(!this.checked1){
			this.$message.error(`请勾选用户协议及隐私条款！`)
			return
		}
      this.$refs.loginForm.validate((valid) => {
        const user = {
          username: this.loginForm.username,
          password: this.loginForm.password,
          rememberMe: this.loginForm.rememberMe,
          code: this.loginForm.code,
          uuid: this.loginForm.uuid,
          clientId: this.loginForm.clientId,
        };
        if (user.password !== this.cookiePass) {
          user.password = encrypt(user.password);
        }
        if (valid) {
          this.loading = true;
          if (user.rememberMe) {
            localStorage.setItem('username', user.username);
            localStorage.setItem('password', user.password);
            localStorage.setItem('rememberMe', user.rememberMe);
          } else {
            localStorage.removeItem('username');
            localStorage.removeItem('password');
            localStorage.removeItem('rememberMe');
          }
          this.$store
            .dispatch('Login', user)
            .then(() => {
              this.loading = false;
              location.reload();
              this.cancel();
            })
            .catch(() => {
              this.loading = false;
              this.getCode();
            });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss">
.tab {
  margin-top: -40px;

  .el-form {
    margin-top: 20px;
  }

  .el-tabs__nav-wrap::after {
    display: none;
  }

  .el-input__inner {
    border-radius: 100px;
    border: none;
    background: #f5f5f5;
  }
}

.code-box {
  position: relative;
  width: 160px;
  height: 160px;
  margin: 20px auto;

  .failure {
    width: 160px;
    height: 160px;
    position: absolute;
    top: 0;
    left: 0;
    background: rgba(225, 225, 225, 0.95);

    p {
      margin-top: 50px;
      color: #1a1a1a;
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 15px;
    }
  }
}

.login-code {
  width: 33%;
  display: inline-block;
  height: 40px;
  float: right;

  img {
    border-radius: 5px;
    cursor: pointer;
	height: 38px;
	padding-top: 2px;
    vertical-align: middle;
  }
}
</style>
